<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>计算属性</title>
	</head>
	<body>
		<div id="example">
			<p>Original message: {{ message }}</p>
			<p>Computed reversed message: {{ reversedMessage}}</p>
		</div>
		
		<div id="demo1">{{fullName}}</div>
		<div id="demo2">{{fullName}}</div>
		
		<div id="watch-example">
			<p>
				Ask a yes/no question:
				<input v-model="question">
			</p>
			<p>{{ answer }}</p>
		</div>
	</body>
	<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
	<script>
		var watchExampleVm = new Vue({
			el:'#watch-example',
			data:{
				question:'',
				answer:'I cannot give you an answer until you ask a question!'
			},
			watch:{
				question:function(newQuestion, oldQuestion){
					this.answer = 'Waiting for you to stop typing......';
					this.debouncedGetAnswer()
				}
			},
			created:function(){
				this.debouncedGetAnswer = _.debounce(this.getAnswer,500);
			},
			methods:{
				getAnswer:function(){
					if(this.question.indexOf('?') === -1){
						this.answer = 'Questions usually contain a question mark. ;-)';
						return
					}
					this.answer = 'Thinking......';
					var vm = this;
					axios.get('https://yesno.wtf/api')
						.then(function(response){
							vm.answer = _.capitalize(response.data.answer);
						})
						.catch(function(error){
							vm.answer = 'Error! Could not reach the API. ' + error
						});
				}
			}
		});
		
		var vm = new Vue({
			el:"#example",
			data:{
				message:'Hello'
			},
			computed:{
				//计算属性的getter
				reversedMessage:function(){
					return this.message.split('').reverse().join('');
				},
				now:function(){
					return Date.now();
				}
			},
		});
		var vm1 = new Vue({
			el:'#demo1',
			data:{
				firstName:'Foo',
				lastName:'Bar',
				fullName:'Foo Bar'
			},
			watch:{
				firstName:function(val){
					this.fullName = val + ' ' + this.lastName;
				},
				lastName:function(val){
					this.fullName = this.firstName + ' ' + val;
				}
			}
		});
		
		var vm2 = new Vue({
			el:'#demo2',
			data:{
				firstName:'Foo',
				lastName:'Bar',
			},
			computed:{
				fullName:function(){
					return this.firstName + ' ' + this.lastName;
				}
			}
		})
	
	</script>
</html>